<!--  -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>学生图书管理</el-breadcrumb-item>
      <el-breadcrumb-item>图书列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--<el-button class="book-table-add" type="success" size="small" @click="showEditForm">添加图书</el-button>-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入图书名称"
                    clearable
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showEditForm">添加图书</el-button>
        </el-col>
      </el-row>
      <el-table
          :data="books"
          @selection-change="handelSelectChange"
          ref="bookRef"
          border
          height="490"
          stripe
      >
        <template slot="empty" v-if="books!=null&&books.length===0">
          <i class="el-icon-loading"></i>
          <span>玩命加载中...</span>
        </template>
        <el-table-column type="expand" align="center">
          <template slot-scope="props">
            <el-form label-position="left" inline>
              <el-form-item>
                <span>{{ props.row.abs }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="title" label="书名(展开查看摘要)" fit align="center"></el-table-column>
        <el-table-column prop="category.name" label="分类" width="100" align="center"></el-table-column>
        <el-table-column prop="num" label="数量" fit align="center"></el-table-column>
        <el-table-column prop="author" label="作者" fit align="center"></el-table-column>
        <el-table-column prop="date" label="出版日期" width="120" align="center"></el-table-column>
        <el-table-column prop="press" label="出版社" fit align="center"></el-table-column>
        <el-table-column prop="position" label="位置" width="0" align="center"
                         v-if="posiotionshow ===false"></el-table-column>
        <el-table-column fixed="right" label="操作" width="220" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="copyBook(scope.row)">复制</el-button>
            <el-button type="primary" size="small" @click="editBook(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteBook(scope.row.rfid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="book-table-footer">
        <el-button type="primary" size="small" @click="cancleSelect">取消选择</el-button>
        <el-button type="danger" size="small">批量删除</el-button>
      </div>
    </el-card>

    <el-dialog title="添加图书/修改图书信息" :visible.sync="dialogFormVisible" @close="closeDialog" width="40%">
      <el-form v-model="form" label-position="right" height="300">
        <el-form-item label="图书isbn" :label-width="labelWidth" v-if="addOrUpdateTag">
          <el-input v-model="form.isbn" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书名" :label-width="labelWidth">
          <el-input v-model="form.title" auto-complete="off" placeholder="不加《》"></el-input>
        </el-form-item>
        <el-form-item label="作者" :label-width="labelWidth">
          <el-input v-model="form.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版日期" :label-width="labelWidth">
          <el-input v-model="form.date" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版社" :label-width="labelWidth">
          <el-input v-model="form.press" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否被借走" :label-width="labelWidth">
          <el-input v-model="form.isborrow" autocomplete="off" placeholder="0代表没有被借走，1代表被借走"></el-input>
        </el-form-item>
        <el-form-item label="封面" :label-width="labelWidth">
          <el-input v-model="form.cover" autocomplete="off" placeholder="图片 URL"></el-input>
          <img-upload @onUpload="uploadImg" ref="imgUpload" v-on:onUpload="uploadImg"></img-upload>
        </el-form-item>
        <el-form-item label="简介" :label-width="labelWidth">
          <el-input type="textarea" v-model="form.abs" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="RFID编号" :label-width="labelWidth" v-if="this.addOrUpdateTag === 1">
          <el-autocomplete
              v-model="form.rfid"
              :fetch-suggestions="querySearchAsync"
              placeholder="请扫描RFID标签"
              @select="handleSelect">
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="选择仓库" :label-width="labelWidth" v-if="this.addOrUpdateTag === 1">
          <el-select v-model="query.id"
                     @change="getPosition"
                     placeholder="请选择您的入库方式">
            <el-option
                v-for="item in warehouseId"
                :key="item.id"
                :label="item.num"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!--级联选择器-->
        <el-form-item label="存储位置" :label-width="labelWidth" v-if="this.addOrUpdateTag === 1">
          <div class="block">
            <span class="demonstration"></span>
            <el-cascader
                placeholder="请输入"
                :options="position"
                filterable
                v-model="form.position"></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="分类" :label-width="labelWidth">
          <el-select v-model="form.category.id" placeholder="请选择分类">
            <el-option label="文学" value="1"></el-option>
            <el-option label="流行" value="2"></el-option>
            <el-option label="文化" value="3"></el-option>
            <el-option label="生活" value="4"></el-option>
            <el-option label="经管" value="5"></el-option>
            <el-option label="科技" value="6"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible =false">取消</el-button>
        <el-button @click="onSubmit" type="primary">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ImgUpload from "./ImgUpload";
import {Message, MessageBox} from "element-ui";

export default {
  data() {
    return {
      labelWidth: "90px",
      queryInfo1: {
        name: '',
        state: 0,
        isread: 1
      },
      query: {
        id: '',
      },
      form: {
        isbn: '',
        cover: '',
        title: '',
        author: '',
        date: '',
        press: '',
        abs: '',
        cid: '',
        rfid: '',
        isborrow: '',
        category: {
          id: ''
        },
        position: '',
        tag: '',
        iscopy: 0
      },
      dialogFormVisible: false,
      warehouseId: [],
      position: [],
      posiotionshow: true,
      // addOrUpdateTag: !this.form.title ? 1 : 0,
      addFormRules: {
        username: [{required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 16, message: "长度在3到16个字符", trigger: "blur"}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 10, message: "长度在3到10个字符", trigger: "blur"}],
        name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
        phone: [{required: true, message: '请输入您的联系方式', trigger: 'blur'},
          {min: 11, max: 11, message: "格式错误", trigger: "blur"}],
        /*email: [{required: true, message: '请输入您的邮箱', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}]*/
      },
      dialogVisible: false, //初始时不显示
      books: [], //初始化的图书数据
      book: {}, //修改之后的单个图书数据
      multiSelect: [],
      initBook: {
        isbn: "",
        title: "",
        author: "",
        date: "",
        press: "",
        cover: "",
        abs: "",
        cid: "",
        rfid: "",
        isborrow: "",
        category: {
          id: "",
          name: ""
        },
        position: "",
        tag: 1,
        iscopy: 0
      }
    };
  },
  components: {
    ImgUpload
  },
  computed: {
    tableHeight() {
      return window.innerHeight - 320;
    },
    newBook() {
      return this.book;
    },
    //添加或者更新的标志
    addOrUpdateTag() {
      console.log(this.form.isbn)
      //添加的为1,修改的为0
      let res = !!this.form.tag ? 1 : 0;
      return res;
    }
  },
  methods: {
    //添加图书
    async onSubmit() {
      let api = this.addOrUpdateTag === 1 ? `addBook` : `updateBook`;

      const pid = this.form.position;
      console.log(pid);
      let position1 = null;
      if (pid != null) {
        if (this.form.iscopy == 0) {
          position1 = pid[pid.length - 1];
        } else {
          position1 = pid;
        }

      }
      let param = {
        isbn: this.form.isbn,
        cover: this.form.cover,
        title: this.form.title,
        author: this.form.author,
        date: this.form.date,
        press: this.form.press,
        abs: this.form.abs,
        cid: this.form.category.id,
        isborrow: Number(this.form.isborrow),
        position: position1,
        rfid: this.form.rfid
      }

      console.log(api);
      console.log(param);
      //添加图书
      const res = await this.$http.post(`/api/${api}`, param)
          .then(res => {
            if (res && res.status === 200) {
              console.log(res)
              Message.success("操作成功！");
              /*this.$message({
                message: "操作成功！",
                type: "success"
              });*/
            }
          })
          .catch(error => {
            console.log(error);
          });
      this.getBooksData(); //初始化获取数据
      this.closeDialog();
    },
    //远程查询RFID编号
    async querySearchAsync(queryString, cb) {
      this.queryInfo1.name = queryString;
      console.log('查询学生信息');
      console.log(this.queryInfo1)
      const res = await this.$http.get('/warehouse/RFID/', {params: this.queryInfo1});
      console.log(res);
      for (let i of res.obj) {
        i.value = i.data;
      }
      cb(res.obj);
    },
    handleSelect(item) {
      this.form.rfid = item.data;
    },
    async getWarehouseId() {
      const res = await this.$http.get('/warehouse/getWarehouseId');
      if (res) {
        console.log(res)
        this.warehouseId = res.obj;
      }
    },
    async getPosition() {
      console.log(this.query);
      const res = await this.$http.get('/warehouse/position/', {params: this.query});
      this.position = res.obj;
      console.log(res);
    },
    async location(item) {
      //console.log(item.id);
      this.locationDialog = true;
      const res = await this.$http.get('/goods/goodsPosition/' + item.id);
      if (res) {
        this.locations = res.obj;
      }

    },
    //上传图片
    uploadImg(url) {
      this.form.cover = url;

    },
    closeDialog() {
      this.dialogvis = false;
      this.dialogFormVisible = false;
      this.form = {
        isbn: '',
        cover: '',
        title: '',
        author: '',
        date: '',
        press: '',
        abs: '',
        cid: '',
        isborrow: '',
        rfid: '',
        category: {
          id: '',
          name: ''
        },
        position: '',
        tag: '',
        iscopy: 0
      };
    },


    //获取所有的图书资料
    async getBooksData() {
      console.log('查询所有图书');
      const res = await this.$http.get('/api/getAllBooks');
      if (res && res.status === 200) {
        console.log(res.obj);
        console.log('查询所有图书完毕');
        this.books = res.obj;
      }
      /*let _this = this;
      _this.$api.bookApi.getAllBooks().then(res => {
        if (res && res.data.code === 200) {
          console.log(res);
          this.books = res.data.data;
        }
      });*/
    },
    //修改图书信息
    editBook(val) {
      console.log(val);

      this.form = {
        isbn: val.isbn,
        cover: val.cover,
        title: val.title,
        author: val.author,
        date: val.date,
        press: val.press,
        abs: val.abs,
        rfid: val.rfid,
        isborrow: val.isborrow === 0 ? "否" : "是",
        category: {
          id: `${val.category.id}`,
          name: val.category.name
        }
      };
      console.log(this.form);
      //this.book = newBook; //将新的图书信息赋值给newBook
      this.dialogFormVisible = true;
    },

    //复制图书信息
    copyBook(val) {
      console.log(val);

      this.form = {
        isbn: val.isbn,
        cover: val.cover,
        title: val.title,
        author: val.author,
        date: val.date,
        press: val.press,
        abs: val.abs,
        rfid: '',
        position: val.position,
        isborrow: val.isborrow === 0 ? "否" : "是",
        category: {
          id: `${val.category.id}`,
          name: val.category.name
        },
        tag: 1,
        iscopy: 1
      };
      console.log(this.form);
      //this.book = newBook; //将新的图书信息赋值给newBook
      this.dialogFormVisible = true;
    },
    //删除图书信息
    async deleteBook(rfid) {
      MessageBox.confirm("此操作将永久删除该图书, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        if (rfid == null) {
          Message.error("无rfid");
          return;
        }
        const res = await this.$http.delete('/api/deleteBook/' + rfid)
        console.log(res);
        if (res && res.status === 200) {
          Message({
            message: "删除成功！",
            type: "success"
          });
          this.getBooksData(); //重新加载图书信息
        }
      }).catch(() => {
            MessageBox({
              type: "info",
              message: "已取消删除"
            });
          });
    },
    //显示对话框 不能直接在DOM上操作dialogVisible
    showEditForm() {
      this.dialogFormVisible = true;
      this.dialogVisible = true;
      this.book = this.initBook;
      this.form.tag = 1;
    },
    //改变对话框显示与否
    changeDialogVisible(val) {
      this.dialogVisible = val;
    },
    //处理选中当前图书的状态
    handelSelectChange(val) {
      this.multiSelect = val;
    },
    cancleSelect() {
      this.$refs.bookRef.clearSelection();
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    console.log("查询所有数据");
    this.getBooksData(); //初始化获取数据
    this.getWarehouseId();
    //这个地方如果初始化时，不赋值为空对象，会报错id undefined
    this.book = this.initBook;
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  }
};
</script>
<style lang="less" scoped>
/* @import url(); 引入css类 */
.book-table-main {
  width: 90%;
}

.book-table-add {
  margin: 18px 0 4px 10px;
}

.book-table-footer {
  margin-top: 20px;
}
</style>